<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin extends CI_Controller {
    protected $data = array();

    public function __construct() {
        parent::__construct();
        $this->load->library('pagination');
        $this->load->model('menu');
        $this->load->model('page');
        $this->load->model('auction');
        $this->load->model('document');
        $this->load->model('contact');
        $this->load->model('pagedocument');
    }

    public function index() {
        if ($this->session->userdata('logged_in')) {
            $data['title'] = 'Interfata administrare -- Bun venit';
            $this->load->view('admin_head', $data);
            $this->load->view('admin_navi', $data);
            $this->load->view('admin_content', $data);
        } else {
           $data['title'] = 'ACSIS Solv I.P.U.R.L';
            $this->load->view('admin_login', $data);
        }
    }

    public function licitatii($view='list', $id=0, $page=0) {
        $data['title'] = 'Interfata administrare -- Licitatii';
        $data['message'] = '';
        $data['contacts'] = array();
        if (!$this->session->userdata('logged_in')) {
            redirect('admin', 'refresh');
        }
        if ($view != 'list') {
            if ($id == 0) {
                $data['auction'] = FALSE;
                $data['form_route'] = 'save';
            } else {
                $data['auction'] = $this->auction->getAuctions(array('auc_id' => $id));
                $data['form_route'] = 'save/' . $id;
            }
            if ($data['auction'] != FALSE) {
                $data['auction']['owner'] = $this->contact->getContacts(array('cnt_id' => $data['auction']['auc_owner']));
                $data['auction']['contact'] = $this->contact->getContacts(array('cnt_id' => $data['auction']['auc_contact']));
            }
            $data['cnts'] = $this->contact->getContacts(array());
            if ($data['cnts']!=FALSE) {
                foreach($data['cnts'] as $cnt) {
                    $data['contacts'][$cnt['cnt_id']] = $cnt['cnt_firstname'] . ' ' . $cnt['cnt_lastname'];

                }
            }
        }
        if ($view == 'save') {
            $this->form_validation->set_message('required', 'Campul %s este obligatoriu.');
            $this->form_validation->set_message('alpha', 'Campul %s accepta doar valori alfanumerice.');
            $this->form_validation->set_message('numeric', 'Campul %s accepta doar valori numerice.');
            $this->form_validation->set_message('valid_email', 'Campul %s nu contine o adresa de email valida.');
            $this->form_validation->set_rules('frmAuctionName', 'Denumire', 'required|xss_clean');
            $this->form_validation->set_rules('frmAuctionDesc', 'Descrierea bunului', 'required|xss_clean');
            $this->form_validation->set_rules('frmAuctionDateStart', 'Data', 'required|xss_clean');
            $this->form_validation->set_rules('frmAuctionType', 'Tipul bunului', 'required|alpha|xss_clean');
            $this->form_validation->set_rules('frmAuctionPrice', 'Pret pornire', 'required|numeric|xss_clean');
            $this->form_validation->set_rules('frmAuctionOwner', 'Societate', 'required|natural|xss_clean');
            $this->form_validation->set_rules('frmAuctionContact', 'Persoana de contact', 'required|natural|xss_clean');
            if ($this->form_validation->run() == FALSE) {
                $data['message'] .= '<p>' . validation_errors() . '</p>';
            } else {
                /*todo:
                 * redirect to contact form twice if needed to add owner and contact person
                 * save to database the auction and two contacts (if needed) as transaction*/
                 $owner = $this->input->post('frmAuctionOwner');
                 $contact = $this->input->post('frmAuctionContact');
                 $auction = array('auc_name' => $this->input->post('frmAuctionName'),
                                  'auc_description' => $this->input->post('frmAuctionDesc'),
                                  'auc_type' => $this->input->post('frmAuctionType'),
                                  'auc_startdate' => strftime('%Y-%m-%d %H:%M:%S', strtotime($this->input->post('frmAuctionDateStart'))),
                                  'auc_startprice' => $this->input->post('frmAuctionPrice'),
                                  'auc_owner' => $owner,
                                  'auc_contact' => $contact
                                 );
                 if ($id == 0) {
                   $aucid = $this->auction->insertAuction($auction);
                   if ($aucid != FALSE) {
                       $auction = $this->auction->getAuctions(array('auc_id'=>$aucid));
                   }
                 } else {
                   $auction = _default(array('auc_id'=>$id), $auction);
                   if ($this->auction->updateAuction($auction) > 0) 
                       $auction = $this->auction->getAuctions(array('auc_id' => $id));
                    else
                       $auction = FALSE;
                 }
                 if ($auction != FALSE) {
                    if (isset($_FILES['frmAuctionDocs'])) {
                        $files = $_FILES['frmAuctionDocs'];
                        foreach ($files['name'] as $key=>$value) {
                            if (is_uploaded_file($files['tmp_name'][$key]) && $files['error'][$key] == 0) {
                                $filename = str_replace(' ', '_', basename($files['name'][$key]));
                                if (move_uploaded_file($files['tmp_name'][$key], $_SERVER['DOCUMENT_ROOT'] . '/documents/' . $filename)) {
                                    $docid = $this->document->insertDocument(array('doc_name'=> pathinfo($filename, PATHINFO_FILENAME),
                                                                      'doc_description' => 'Documentatie licitatie: '. $auction['auc_name'],
                                                                      'doc_path' => 'documents/' . $filename,
                                                                      'doc_owner' => $auction['auc_owner'],
                                                                      'doc_contact' => $auction['auc_contact'],
                                                                      'doc_type' => 'O'));
                                    if ($docid)
                                        $this->pagedocument->addDocumentToPage(array('dp_document'=>$docid, 'dp_page'=>$auction['auc_detailpage']));
                                 } else {
                                     $data['message'] .= '<p>Eroare la upload: ' .$files['name'][$key] .'. Verifica spatiul</p>';
                                 }
                            } else {
                                $data['message'] .= '<p>Eroare la upload: ' .$files['name'][$key] .'</p>';
                            }
                        }
                    }
                    if (isset($_FILES['frmAuctionLogo'])) {
                        $files = $_FILES['frmAuctionLogo'];
                        if (is_uploaded_file($files['tmp_name']) && $files['error'] == 0) {
                            $filename = str_replace(' ', '_', basename($files['name']));
                            if (move_uploaded_file($files['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/logos/' . $filename)) {
                                $this->auction->updateAuction(array('auc_id' => $auction['auc_id'], 'auc_logopath' => '/logos/' . $filename));
                            } else {
                                $data['message'] .= '<p>Eroare la upload: ' .$files['name'][$key] .'. Verifica spatiul</p>';
                            }
                        } else {
                            $data['message'] .= '<p>Eroare la upload: ' .$files['name'] . '</p>';
                        }
                    }
                 }
                 $addcontacts = false;
                 if ($owner == 0) {
                     $addcontacts = true;
                     $this->session->set_userdata(array('auction' => $aucid,
                                                        'addowner' => TRUE));

                 }
                 if ($contact == 0) {
                     $addcontacts = true;
                     $this->session->set_userdata(array('auction'=>$aucid,
                                                        'addcontact' => TRUE));
                 }
                 if ($addcontacts) {
                     redirect('admin/contacte/addnew');
                 } else {
                    redirect('admin/licitatii/list', 'refresh');
                 }
            }
        } else if ($view == 'saved'){
            /*saved*/
        } else {
            $data['auctions'] = $this->auction->getAuctions(array('limit' => 5, 'offset' => $page));
            $count = $this->auction->countAuctions(array());
            if ($data['auctions'] != FALSE) {
                $pagconf = array('base_url' => base_url() . '/admin/licitatii/' . $view . '/0/',
                                                     'total_rows' => $count,
                                                     'per_page' => 5,
                                                     'uri_segment' => 5);
                $this->pagination->initialize($pagconf);
                $data['links'] = $this->pagination->create_links();
                foreach ($data['auctions'] as &$auction) {
                    $auction['owner'] = $this->contact->getContacts(array('cnt_id' => $auction['auc_owner']));
                    $auction['contact'] = $this->contact->getContacts(array('cnt_id' => $auction['auc_contact']));
                }
            }
        }
        switch ($view) {
            case 'form':
            case 'save':
            case 'saved':
                $this->load->view('admin_head', $data);
                $this->load->view('admin_navi', $data);
                $this->load->view('admin_contentauction', $data);
                break;
            case 'list':
                $this->load->view('admin_head', $data);
                $this->load->view('admin_navi', $data);
                $this->load->view('admin_contentauctionlist', $data);
                break;
        }
    }

    public function documente($view='list', $id=0, $page = 0) {
        $data['title'] = 'Interfata administrare -- Documente';
        if (!$this->session->userdata('logged_in')) {
            redirect('admin', 'refresh');
        }
        if ($view != 'list') {
            if ($id != 0) {
                $data['document'] = $this->document->getDocuments(array('doc_id' => $id));
                $data['form_route'] = 'save/' . $id;
            } else {
                $data['document'] = FALSE;
                $data['form_route'] = 'save';
            }
            $cnts = $this->contact->getContacts();
            if ($cnts!=FALSE) {
                foreach($cnts as $cnt) {
                    $data['contacts'][$cnt['cnt_id']] = $cnt['cnt_firstname'] . ' ' . $cnt['cnt_lastname'];

                }
            }
        }
        if ($view == 'save') {        
            $this->form_validation->set_message('required', 'Campul %s este obligatoriu.');
            $this->form_validation->set_message('alpha', 'Campul %s accepta doar valori alfanumerice.');
            $this->form_validation->set_message('numeric', 'Campul %s accepta doar valori numerice.');
            $this->form_validation->set_message('valid_email', 'Campul %s nu contine o adresa de email valida.');
            $this->form_validation->set_rules('frmDocumentName', 'Denumire', 'required|xss_clean');
            $this->form_validation->set_rules('frmDocumentDesc', 'Descriere', 'required|xss_clean');
            $this->form_validation->set_rules('frmDocumentType', 'Tipul documentului', 'required|alpha|xss_clean');
            $this->form_validation->set_rules('frmDocumentOwner', 'Societate', 'required|natural|xss_clean');
            $this->form_validation->set_rules('frmDocumentContact', 'Persoana de contact', 'required|natural|xss_clean');
            if ($this->form_validation->run() == FALSE) {
                $data['message'] .= '<p>' . validation_errors() . '</p>';
            } else {
                 $owner = $this->input->post('frmAuctionOwner');
                 $contact = $this->input->post('frmAuctionContact');
                 $document = array('doc_name' => $this->input->post(),
                                   'doc_descriprion' => $this->input->post(),
                                   'doc_type' => $this->input->post,
                                   'doc_owner' => $owner,
                                   'doc_contact' => $contact
                                  );
                 $errors = 0;
                 if (isset($_FILES['frmDocumentFile'])) {
                    $files = $_FILES['frmDocumentFile'];
                    foreach ($files['name'] as $key=>$value) {
                        if (is_uploaded_file($files['tmp_name'][$key]) && $files['error'][$key] == 0) {
                            $filename = str_replace(' ', '_', basename($files['name'][$key]));
                            if (move_uploaded_file($files['tmp_name'][$key], $_SERVER['DOCUMENT_ROOT'] . '/documents/' . $filename)) {
                                $document['doc_path'] = 'documents/' . $filename;
                            } else {
                                $data['message'] .= '<p>Eroare la upload: ' .$files['name'][$key] .'. Verifica spatiul.</p>';
                                $errors++;
                            }                                   
                        } else {
                            $errors++;
                            $data['message'] .= '<p>Eroare la upload: ' .$files['name'][$key] .'</p>';
                        }
                    }
                 }
                 if ($errors == 0) {
                     if ($id == 0) {
                            $docid = $this->document->insertDocument($document);
                            if ($docid != FALSE) {
                                $addcontacts = false;
                                if ($owner == 0) {
                                    $addcontacts = true;
                                    $this->session->set_userdata(array('document' => $docid,
                                                                        'addowner' => TRUE));
                                }
                                if ($contact == 0) {
                                    $addcontacts = true;
                                    $this->session->set_userdata(array('document'=>$docid,
                                                                        'addcontact' => TRUE));
                                }
                                if ($addcontacts) {
                                    redirect('admin/contacte/addnew');
                                } else {
                                    redirect('admin/documente/list', 'refresh');
                                }
                            }
                     } else {
                       $document = _default(array('doc_id'=>$id), $document);
                       if ($this->document->updateDocument($document) > 0) 
                           redirect('admin/documente/list', 'refresh');
                        else {
                           $data['message'] .= '<p>Eroare la actualizarea documentului</p>';
                       }
                     }
                 }
            }
        } else if ($view == 'saved') {
        } else {
            $data['documents'] = $this->document->getDocuments(array('limit' => 5, 'offset' => $page));
            $count = $this->document->countDocuments();
            if ($data['documents'] != FALSE) {
                $pagconf = array('base_url' => base_url() . '/admin/documente/' . $view . '/0/',
                                                     'total_rows' => $count,
                                                     'per_page' => 5,
                                                     'uri_segment' => 5);
                $this->pagination->initialize($pagconf);
                $data['links'] = $this->pagination->create_links();
                
                foreach ($data['documents'] as &$doc) {
                    $doc['owner'] = $this->contact->getContacts(array('cnt_id' => $doc['doc_owner']));
                    /*$doc['contact'] = $this->contact->getContacts(array('cnt_id' => $doc['auc_contact']));*/
                }
            }
        }
        switch ($view) {
            case 'form':
            case 'save':
            case 'saved':
                $this->load->view('admin_head', $data);
                $this->load->view('admin_navi', $data);
                $this->load->view('admin_contentdocument', $data);
            break;
            case 'list':
                $this->load->view('admin_head', $data);
                $this->load->view('admin_navi', $data);
                $this->load->view('admin_contentdocumentlist', $data);
            break;
        }
    }

    public function contacte($view='list', $id=0, $page=0) {
        $data['title'] = 'Interfata administrare -- Contacte';
        $data['message'] = '';
        if (!$this->session->userdata('logged_in')) {
            redirect('admin', 'refresh');
        }
        if ($view != 'list') {
                if ($id != 0) {
                    $data['contact'] = $this->contact->getContacts(array('cnt_id' => $id));
                    $data['form_route'] = 'save/' . $id;
                } else {
                    $data['contact'] = FALSE;
                    $data['form_route'] = 'save';
                }
        } 
        if ($view == 'save') {
                $this->form_validation->set_message('required', 'Campul %s este obligatoriu.');
                $this->form_validation->set_message('alpha', 'Campul %s accepta doar valori alfanumerice.');
                $this->form_validation->set_message('numeric', 'Campul %s accepta doar valori numerice.');
                $this->form_validation->set_message('valid_email', 'Campul %s nu contine o adresa de email valida.');
                $this->form_validation->set_rules('frmContactName', 'Nume', 'required|xss_clean');
                $this->form_validation->set_rules('frmContactPhone', 'Telefon', 'required|xss_clean');
                $this->form_validation->set_rules('frmContactEmail', 'Email', 'required|valid_email|xss_clean');
                $this->form_validation->set_rules('frmContactFax', 'Fax', 'required|xss_clean');
                $this->form_validation->set_rules('frmContactAddr1', 'Adresa', 'required|xss_clean');
                $this->form_validation->set_rules('frmContactRegId', 'CIF', 'required|xss_clean');
                $this->form_validation->set_rules('frmContactTradeRegId', 'RC', 'required|xss_clean');
                if ($this->form_validation->run() == FALSE) {
                    $data['message'] = validation_errors();
                } else {
                    $contact = array('cnt_firstname' => $this->input->post('frmContactName'),
                                     'cnt_lastname' => '',
                                     'cnt_phonenb' => $this->input->post('frmContactPhone'),
                                     'cnt_email' => $this->input->post('frmContactEmail'),
                                     'cnt_faxnb' => $this->input->post('frmContactFax'),
                                     'cnt_addr1' => $this->input->post('frmContactAddr1'),
                                     'cnt_regid' => $this->input->post('frmContactRegId'),
                                     'cnt_traderegid' => $this->input->post('frmContactTradeRegId'));
                    if ($id == 0) {
                        $cntid = $this->contact->insertContact($contact);
                        $docid = $this->session->userdata('document');
                        $aucid = $this->session->userdata('auction');
                        $addowner = $this->session->userdata('addowner');
                        $addcontact = $this->session->userdata('addcontact');
                        $todo = ($addowner!=FALSE || $addcontact!=FALSE);
                        if ($cntid != FALSE && $aucid != FALSE && $todo != FALSE) {
                            if ($addowner) {
                                $aucdata = array('auc_id' => $aucid, 'auc_owner' => $cntid);
                                $this->session->unset_userdata('addowner');
                                $addowner = FALSE;
                            } else if ($addcontact) {
                                $aucdata = array('auc_id' => $aucid, 'auc_contact' => $cntid);
                                $this->session->unset_userdata('addcontact');
                                $addcontact = FALSE;
                            }
                            if ($this->auction->updateAuction($aucdata) == FALSE) {
                                $data['message'] = 'Update fails '. print_r($aucdata);
                            }
                            if ($addowner || $addcontact) {
                                redirect('admin/contacte/addnew');
                            } else {
                                $this->session->unset_userdata('auction');
                                redirect('admin/licitatii/list');
                            }
                        } else if ($cntid != FALSE && $docid != FALSE && $todo != FALSE) {
                            if ($addowner) {
                                $docdata = array('doc_id' => $docid, 'auc_owner' => $cntid);
                                $this->session->unset_userdata('addowner');
                                $addowner = FALSE;
                            } else if ($addcontact) {
                                $docdata = array('doc_id' => $docid, 'auc_contact' => $cntid);
                                $this->session->unset_userdata('addcontact');
                                $addcontact = FALSE;
                            }
                            if ($this->document->updateDocument($docdata) == FALSE) {
                                $data['message'] = 'Update fails '. print_r($docdata);
                            }
                            if ($addowner || $addcontact) {
                                redirect('admin/contacte/addnew');
                            } else {
                                $this->session->unset_userdata('document');
                                redirect('admin/documente/list');
                            }
                        } else {
                            $data['message'] = $cntid . ' ' . $aucid . ' '. $todo;
                        }
                    } else {
                        $contact = _default(array('cnt_id' => $id), $contact);
                        if ($this->contact->updateContact($contact) > 0)
                            redirect('admin/contacte/list');
                        else {
                            $data['message'] = 'Update fails '. print_r($contact);
                        }
                    }
                }
            } else if ($view == 'saved') {
            } else if ($view == 'list') {
                $data['contacts'] = $this->contact->getContacts(array('limit' => 30, 'offset' => $page));
                $count = $this->contact->countContacts();
                if ($data['contacts'] != FALSE) {
                    $pagconf = array('base_url' => base_url() . '/admin/contacts/' . $view . '/0/',
                                                         'total_rows' => $count,
                                                         'per_page' => 30,
                                                         'uri_segment' => 5);
                    $this->pagination->initialize($pagconf);
                    $data['links'] = $this->pagination->create_links();
                }
            }
            switch ($view) {
                case 'form':
                case 'save':
                case 'saved':
                    $this->load->view('admin_head', $data);
                    $this->load->view('admin_navi', $data);
                    $this->load->view('admin_contentcontact', $data);
                    break;
                case 'list':
                    $this->load->view('admin_head', $data);
                    $this->load->view('admin_navi', $data);
                    $this->load->view('admin_contentcontactlist', $data);
                break;
            }
    }

    public function login() {
        $this->form_validation->set_message('required', 'Campul %s este obligatoriu.');
        $this->form_validation->set_message('alpha', 'Campul %s accepta doar valori alfanumerice.');
        $this->form_validation->set_message('valid_email', 'Campul %s nu contine o adresa de email valida.');
        $this->form_validation->set_rules('frmLoginName', 'Nume', 'trim|required|alpha|xss_clean');
        $this->form_validation->set_rules('frmLoginPasswd', 'Parola', 'required|xss_clean|callback_checklogin');
        if ($this->form_validation->run() === FALSE) {
            $data['title'] = 'Userul sau parola nu sunt valide.';
            $data['errors'] = validation_errors();
            $this->load->view('admin_login', $data);
        } else {
            redirect('admin', 'refresh');
        }
    }
    public function logout() {
        $this->session->unset_userdata('logged_in');
        $this->session->sess_destroy();
        redirect('admin', 'refresh');
    }

    public function checklogin($password) {
        /*todo:
         * add check against database*/
        if ($password == 'tractor') {
            $this->session->set_userdata('logged_in', TRUE);
            return TRUE;
        } else {
            $this->form_validation->set_message('checklogin', 'Parola nu este valida.');
            return FALSE;
        }
    }
}
